package mrusanov.ui.stats

import javax.swing.{JLabel, JPanel}
import mrusanov.tournament.{MatchInfo, KnockOutTournamentRound}
import java.awt.{Font, GridLayout}
import mrusanov.team.Team

class KnockoutTournamentRoundPanel(round:KnockOutTournamentRound) extends JPanel {
  private val teamsWhoWon = round.passedRound.toSet
  private val results = round.groupMatchesByPairs()

  setLayout(new GridLayout(0, 3))
  results.foreach(kv => {
    addPair(kv._1._1, kv._1._2, kv._2)
  })

  private def addPair(first:Team, second:Team, games:List[MatchInfo]){
    val firstTeamLabel = new JLabel(first.name)
    val secondTeamLabel = new JLabel(second.name)
    val resultsLabel = new JLabel(turnGamesIntoLine(first, second, games))

    if (teamsWhoWon.contains(first)) {
      setBoldFont(firstTeamLabel)
    } else if (teamsWhoWon.contains(second)) {
      setBoldFont(secondTeamLabel)
    }

    add(firstTeamLabel)
    add(secondTeamLabel)
    add(resultsLabel)
  }

  private def setBoldFont(label:JLabel) {
    label.setFont(label.getFont.deriveFont(Font.BOLD))
  }

  private def turnGamesIntoLine(first:Team, second:Team, games:List[MatchInfo]):String = {
    val results = games.map(getMatchInfoInCorrectOrder(first, second, _))
    results.mkString(",")
  }

  private def getMatchInfoInCorrectOrder(first:Team, second:Team, game:MatchInfo) =
    if (game.host == first) {
      game.hostPoints + ":" + game.guestPoints
    } else {
      game.guestPoints + ":" + game.hostPoints
    }



}
